package qf.sail.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

public class DBUtil {
    private static DataSource dataSource;

    /**
     * 获取数据源
     * @return
     */
    public static DataSource getDataSource() {
        if (null != dataSource) {
            return dataSource;
        }
        try {
            Properties properties = new Properties();
            InputStream resourceAsStream = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            return dataSource;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取beanHandler
     * @param entityClass
     * @param <T>
     * @return
     */
    public static  <T> BeanHandler<T> getBeanHandler(Class<T> entityClass){
        //开启驼峰转换
        BeanProcessor bean = new GenerousBeanProcessor();
        RowProcessor processor = new BasicRowProcessor(bean);
        //返回对应转换结果
        BeanHandler<T> beanHandler = new BeanHandler<>(entityClass,processor);
        return beanHandler;
    }

    /**
     * 获取beanHandler
     * @param entityClass
     * @param <T>
     * @return
     */
    public static  <T> BeanListHandler<T> getBeanListHandler(Class<T> entityClass){
        //开启驼峰转换
        BeanProcessor bean = new GenerousBeanProcessor();
        RowProcessor processor = new BasicRowProcessor(bean);
        //返回对应转换结果
        BeanListHandler<T> beanListHandler = new BeanListHandler<>(entityClass,processor);
        return beanListHandler;
    }
}
